// 导入创建 store 的方法
import { defineStore } from "pinia";
import { ref } from 'vue'
import type { Ref } from 'vue'
interface iUser {
    loginState: boolean;
    userid: string;
    token: string;
    username: string,
    tel: string,
    sex: string,
    birthday: string,
    from: string,
    password: string,
    userarr:any[]
}



// 创建 store
export const useUserStore = defineStore('user', () => {
    // 定义全局状态
    // 用户是否登录
    const loginState: Ref<boolean> = ref(localStorage.getItem('loginState') == 'true')
    // 用户 id 
    const userid: Ref<string> = ref(localStorage.getItem('userid') || '')
    // 用户的 token 
    const username: Ref<string> = ref(localStorage.getItem('username') || '')
    const token: Ref<string> = ref(localStorage.getItem('token') || '')
    const tel: Ref<string> = ref(localStorage.getItem('tel') || '')
    const sex: Ref<string> = ref(localStorage.getItem('sex') || '')
    const from: Ref<string> = ref(localStorage.getItem('from') || '')
    const birthday: Ref<string> = ref(localStorage.getItem('birthday') || '')
    const password: Ref<string> = ref(localStorage.getItem('password') || '')
    const userarr: Ref<any[]> = ref([
        {
            loginState,
            userid,
            username,
            token,
            tel,
            sex,
            from,
            birthday,
            password
        }
    ])
    // 定义一个修改全局状态的方法
    function changeUserState(userInfo: iUser) {
        loginState.value = userInfo.loginState
        userid.value = userInfo.userid
        token.value = userInfo.token
        username.value = userInfo.username
        tel.value = userInfo.tel
        sex.value = userInfo.sex
        birthday.value = userInfo.birthday
        from.value = userInfo.from
        password.value = userInfo.password
        userarr.value.push(userInfo)
        // 将状态存储到本地
        localStorage.setItem('loginState', String(userInfo.loginState))
        localStorage.setItem('userid', userInfo.userid)
        localStorage.setItem('token', userInfo.token)
        localStorage.setItem('username', userInfo.username)
        localStorage.setItem('tel', userInfo.tel)
        localStorage.setItem('sex', userInfo.sex)
        localStorage.setItem('birthday', userInfo.birthday)
        localStorage.setItem('from', userInfo.from)
        localStorage.setItem('password', userInfo.password)
        localStorage.setItem('userarr', String(userarr))
    }

    // 将全局状态中的属性和方法暴露出去
    return {
        loginState,
        userid,
        token,
        username,
        tel,
        sex,
        birthday,
        from,
        password,
        changeUserState
    }
})